<!-- eslint-disable no-undef -->
<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io, { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType } from '@/enums'
import { getOrderDeatil } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
const store = useUserStore()
const route = useRoute()
let socket: Socket
const list = ref<Message[]>([]) // 聊天记录
const isLock = ref(true)
//等DOM渲染完毕后 建立连接 携带token和订单id
onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听连接成功的状态
  socket.on('connect', () => {
    console.log('连接成功')
  })
  // 连接失败
  socket.on('error', (err) => {
    console.log('连接失败', err)
  })
  // 断开连接
  socket.on('disconnect', () => {
    console.log('连接断开')
    // 断开连接后 清空聊天记录
    list.value = []
  })
  // 接收服务器发送的消息 socket.on('事件类型')
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    let arr: Message[] = []
    console.log(data)
    if (!data.length) {
      showToast('没有更多记录了')
      return (loading.value = false)
    }
    // 坑: 下去做聊天记录来 修改成遍历的方式
    data.forEach((item, i) => {
      // 记录第一条聊天记录的时间, 供下一次请求记录的时候使用
      if (i === 0) {
        time.value = item.createTime
      }
      const o = {
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: {
          content: item.createTime
        }
      }
      item.items.unshift(o)

      // 给每一个聊天记录添加一个字段 默认展示的第一次聊天记录的notScroll为false, 后续的聊天记录的notScroll为true
      item.items.forEach((it) => {
        it.notScroll = isLock.value === false
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    // 设置所有消息为已读
    socket.emit('updateMsgStatus', list.value[list.value.length - 1].id)
    // 响应完毕后 将loading关闭
    loading.value = false
    // 取到数据后, 设置滚动条到最底部
    // 需要锁定 只需要第一次加载聊天记录滚动到最底部, 后续加载历史聊天记录的时候就不需要再滚动到底部了
    // 待会处理滚动到底部的bug??????
    if (isLock.value) {
      nextTick(() => {
        // 设置滚动条向下移动
        window.scrollTo(0, document.documentElement.scrollHeight)
      })
      isLock.value = false
    }
  })
  // 问诊订单发生变化后的消息, 重新获取一次订单信息
  socket.on('statusChange', () => {
    getOrderDetailInfo()
  })

  // 接收服务器发送的消息  文字和图片
  socket.on('receiveChatMsg', (res: Message) => {
    console.log(res)
    list.value.push(res) // 将消息追加到聊天记录中
    // 接受一条消息 读取一条消息
    socket.emit('updateMsgStatus', res.id)
    nextTick(() => {
      // 设置滚动条向下移动
      window.scrollTo(0, document.documentElement.scrollHeight)
    })
  })
  // 获取订单详情
  getOrderDetailInfo()
})
const orderInfo = ref<ConsultOrderItem>()
const getOrderDetailInfo = async () => {
  const res = await getOrderDeatil(route.query.orderId as string)
  orderInfo.value = res.data
}
// 离开页面断开连接
onUnmounted(() => {
  socket.close()
})
// 发送消息给医生
const sendMsg = (s: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 用户id
    to: orderInfo.value?.docInfo?.id, // 医生的id
    msgType: MsgType.MsgText, // 消息类型
    msg: {
      content: s
    }
  })
}

// 发送图片消息给医生
const sendImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 用户id
    to: orderInfo.value?.docInfo?.id, // 医生的id
    msgType: MsgType.MsgImage, // 消息类型
    msg: {
      picture: img
    }
  })
}
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  // 获取更多聊天记录
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 依赖注入传递信息
provide('orderInfo', orderInfo)

const setScore = (score: number) => {
  // 找到评价消息 给评价的消息项添加一个score字段
  const o = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (o) {
    o.msg.evaluateDoc = {}
    o.msg.evaluateDoc.score = score
    o.msgType = MsgType.CardEva
  }
}
provide('setScore', setScore)
</script>

<template>
  <div class="room-page">
    <cp-navbar title="医生问诊室" />
    <!-- 状态栏 -->
    <room-status :status="orderInfo?.status" :time="orderInfo?.countdown" />
    <!-- 聊天的消息 -->
    <van-pull-refresh
      v-model="loading"
      success-text="刷新成功"
      @refresh="onRefresh"
    >
      <room-message v-for="item in list" :key="item.id" :item="item" />
    </van-pull-refresh>

    <!-- 聊天输入框和上传图片 -->
    <room-action
      v-if="orderInfo?.status"
      :status="orderInfo?.status"
      @sendMsg="sendMsg"
      @sendImg="sendImg"
    />
  </div>
</template>
<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
